<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="./vue.js"></script>
  <style>
    .in {
      color: red;
    }
  </style>
</head>
<body>
  <template id="shop-item">
    <div>
      <p>
        <span>{{ id }}</span>
        <b>{{ shopTitle }}</b>
        <span>{{ status | formatStatus }}</span>
        <em>{{ price | toFixed2 }}</em>
        <button 
          :class="{ in: isCart }"
          @click="toggleIsCart"
        >
          {{ isCart ? '移出' : '加入' }}购物车
        </button>
      </p>
    </div>
  </template>
  <div id="app">
    <div class="container">
      <shop-item
        v-for="shopItem in list"
        :key="shopItem.id"
        :shop-title="shopItem.shopTitle"
        :is-cart="shopItem.isCart"
        :status="shopItem.status"
        :price="shopItem.price"
        :id="shopItem.id"
        @toggle-is-cart-from-item="toggleIsCartByParent"
      />
    </div>
  </div>
  <script>
    const shopItem = {
      template: '#shop-item',
      props: {
        shopTitle: String,
        status: {
          type: String,
          required: false,
          default: '001'
        },
        id: Number,
        price: Number,
        isCart: Boolean
      },
      methods: {
        toggleIsCart () {
          // 告诉父组件，我要修改当前商品的isCart值了
          // 使用emit向父级触发一个自定义事件
          // 这里的事件名和父组件绑定的事件名必须完全一致
          // 第二个参数可以向父组件传参
          this.$emit('toggle-is-cart-from-item', { id: this.id })
        }
      },
      filters: {
        formatStatus (status) {
          const statusMap = {
            '001': '未付款',
            '002': '待发货',
            '003': '已发货',
            '004': '已签收',
            '005': '已评价'
          }
          return statusMap[status]
        },
        toFixed2 (num) {
          return num.toFixed(2)
        }
      }
    }

    const app = new Vue({
      el: '#app',
      data: {
        list: [
          { id: 1, status: '001', isCart: false, shopTitle: '拖把', price: 19.99999 },
          { id: 2, status: '004', isCart: false, shopTitle: '扫把', price: 9 },
          { id: 3, status: '003', isCart: true, shopTitle: '簸箕', price: 29.1 },
          { id: 4, status: '002', isCart: false, shopTitle: '吸尘器', price: 2999.159839 },
          { id: 5, status: '005', isCart: false, shopTitle: '鸡毛掸子', price: 23.19 }
        ]
      },
      components: {
        shopItem
      },
      methods: {
        toggleIsCartByParent ({ id }) {
          console.log(id)
          // 根据id修改list
          // props传递时单向的，而且是响应式的，也就是说父组件的data被修改了，传递到子组件的props也就响应式的被修改了
          this.list = this.list.map(shop => {
            if (shop.id === id) shop.isCart = !shop.isCart
            return shop
          })
        }
      }
    })
  </script>
</body>
</html>
